<template>
  <van-overlay :show="isShow" @click="isShow = false" z-index="2">
    <div class="trtcCalling-container" @click.stop>
      <!--        <div class="trtcCalling-fullscreen">
                  <Icon
                    :custom="fullscreen ? 'iconfont iconsuoxiao' : 'iconfont iconfangda'"
                    size="24"
                    @click="fullscreen = !fullscreen"
                  />
                </div>-->
      <div class="trtcCalling-answer-title" v-show="statusName === '接听'">
        <div class="trtcCalling-duration">{{ durationFormat }}</div>
        <!--          <div class="trtcCalling-video-item" :class="{ 'video-big': isVideoClick }">
                      <div class="trtcCalling-video-item-inner" id="video-big" @click="handleVideoClick"></div>
                      <p class="trtcCalling-answer-title-name" v-show="!videoChangeFlag">{{ bigUserName }}</p>
                    </div>
                    <div class="trtcCalling-video-item" :class="{ 'video-small': isVideoClick }">
                      <div class="trtcCalling-video-item-inner" id="video-small" @click="handleVideoClick"></div>
                      <p class="trtcCalling-video-item-text">{{ smallUserName }}</p>
                    </div>-->
      </div>
      <div class="trtcCalling-video">
        <div class="trtcCalling-video-big" id="video-big"></div>
        <div class="trtcCalling-video-small" id="video-small-warp" v-drag>
          <div class="trtcCalling-video-small-video" id="video-small" @click="handleVideoClick"></div>
          <p class="trtcCalling-video-small-text" v-show="!videoChangeFlag">{{ smallUserName }}</p>
        </div>
      </div>
      <div class="trtcCalling-call-title" v-show="statusName !== '接听'">
        <p class="trtcCalling-call-title-text">{{ statusName }}</p>
        <p class="trtcCalling-call-title-name">{{ callPerson.gridPersonName }}</p>
        <p class="trtcCalling-call-title-name">...</p>
      </div>
      <div class="trtcCalling-operate" v-show="statusName === '接听'">
        <van-row>
          <van-col :span="8" align="center">
            <img
              :src="require(`@/assets/images/trtc/icon_audio_${isAudioAvailable ? 'off' : 'on'}@2x.png`)"
              class="trtcCalling-operate-img"
              alt=""
              @click="handleChangeAudioAvailable"
            />
            <p class="trtcCalling-operate-text">{{ isAudioAvailable ? '静音' : '取消静音' }}</p>
          </van-col>
          <van-col :span="8" align="center">
            <img
              src="@/assets/images/trtc/icon_cancel@2x.png"
              class="trtcCalling-operate-img"
              alt=""
              @click="handleCancel"
            />
            <p class="trtcCalling-operate-text">挂断</p>
          </van-col>
          <van-col :span="8" align="center">
            <img
              src="@/assets/images/trtc/icon_camera_change.png"
              class="trtcCalling-operate-img"
              alt=""
              @click="handleChangeVideoAvailable"
            />
            <p class="trtcCalling-operate-text">转换摄像头</p>
          </van-col>
        </van-row>
      </div>
    </div>
  </van-overlay>
</template>
<script>
import { mapState } from 'vuex'
import { createTrtcCalling, getUserSig } from '@/trtc'
import { formatTimes } from '@/libs/tool'
export default {
  name: 'call',
  data() {
    return {
      isShow: false,
      fullscreen: false,
      // 视频通话
      trtcCalling: null,
      // 本地用户UserId
      localUserId: '',
      // 大框中用户名称
      bigUserName: '',
      // 小框中用户名称
      smallUserName: '',
      // 邀请状态
      statusName: '呼叫中',
      // 是否静音
      isAudioAvailable: true,
      // 是否关闭摄像头
      isVideoAvailable: true,
      // 确认框
      remindData: {
        showRemind: false,
        remindTitle: '提示',
        content: '是否结束通话？'
      },
      // 视频切换
      videoChangeFlag: true,
      isVideoClick: false,
      // 摄像头切换
      cameras: [],
      camerasIndex: 0,
      // 计时
      timer: null,
      duration: 0,
      durationFormat: '',
      callPerson: {}
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  created() {
    if (this.user.token) {
      // 初始化视频通话
      this.initTrtcCalling()
    } else {
      // 视频通话 - 退出登录
      this.removeListener()
      this.trtcCalling.logout()
    }
    window.TRTC.getCameras().then(devices => {
      this.cameras = devices
    })
    // window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
  mounted() {
    this.$eventBus.$on('trtcCallingCall', data => {
      this.callPerson = data
      this.bigUserName = this.user.userName
      this.smallUserName = this.callPerson.gridPersonName
      this.statusName = '呼叫中'
      this.isShow = true
      this.call().catch(() => {
        this.statusName = '对方未上线'
      })
    })
  },
  methods: {
    // 初始化视频通话
    initTrtcCalling() {
      this.localUserId = this.user.token + '-' + this.user.userName
      this.trtcCalling = createTrtcCalling()
      this.trtcCalling.logout()
      this.trtcCalling.login({
        userID: this.user.phone,
        userSig: getUserSig(this.user.phone)
      })
      this.initListener()
    },
    beforeunloadHandler(e) {
      e = e || window.event
      if (e) {
        e.returnValue = '关闭提示'
        // localStorage.clear()
        this.removeListener()
        this.trtcCalling.logout()
      }
    },
    // 呼叫
    async call() {
      await this.trtcCalling.call({
        userID: this.callPerson.telephone,
        type: window.TRTCCalling.CALL_TYPE.VIDEO_CALL,
        timeout: this.$config.callTimeout
      })
    },
    // 挂断
    handleCancel(hangup) {
      hangup && this.trtcCalling.hangup()
      this.isShow = false
      this.isVideoAvailable = true
      this.isVideoClick = false
      this.duration = 0
      this.durationFormat = ''
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      setTimeout(() => {
        this.statusName = ''
        this.isAudioAvailable = true
        this.videoChangeFlag = true
        document.getElementById('video-small-warp').style.left = 'auto'
        document.getElementById('video-small-warp').style.right = '32px'
        document.getElementById('video-small-warp').style.top = '28px'
      }, 200)
      // localStorage.clear()
    },
    // 初始化监听事件
    initListener() {
      // 被邀用户拒绝通话
      this.trtcCalling.on(window.TRTCCalling.EVENT.REJECT, this.handleInviteeReject)
      // 被邀用户正在通话中，忙线
      this.trtcCalling.on(window.TRTCCalling.EVENT.LINE_BUSY, this.handleInviteeLineBusy)
      // 被邀用户超时无应答
      this.trtcCalling.on(window.TRTCCalling.EVENT.NO_RESP, this.handleNoResponse)
      // 用户进房
      this.trtcCalling.on(window.TRTCCalling.EVENT.USER_ENTER, this.handlecaaUserEnter)
      // 用户退出房间
      this.trtcCalling.on(window.TRTCCalling.EVENT.USER_LEAVE, this.handleUserLeave)
      // 重复登录，被踢出房间
      this.trtcCalling.on(window.TRTCCalling.EVENT.KICKED_OUT, this.handleKickedOut)
      // 远端用户开启/关闭了摄像头
      this.trtcCalling.on(window.TRTCCalling.EVENT.USER_VIDEO_AVAILABLE, this.handleUserVideoChange)
      // 远端用户开启/关闭了麦克风
      this.trtcCalling.on(window.TRTCCalling.EVENT.USER_AUDIO_AVAILABLE, this.handleUserAudioChange)
      // 本次通话结束
      this.trtcCalling.on(window.TRTCCalling.EVENT.CALLING_END, this.handleCallEnd)
      // 错误回调
      this.trtcCalling.on(window.TRTCCalling.EVENT.ERROR, this.handleError)
    },
    // 移除监听事件
    removeListener() {
      // 被邀用户拒绝通话
      this.trtcCalling.off(window.TRTCCalling.EVENT.REJECT, this.handleInviteeReject)
      // 被邀用户正在通话中，忙线
      this.trtcCalling.off(window.TRTCCalling.EVENT.LINE_BUSY, this.handleInviteeLineBusy)
      // 被邀用户超时无应答
      this.trtcCalling.off(window.TRTCCalling.EVENT.NO_RESP, this.handleNoResponse)
      // 用户进房
      this.trtcCalling.off(window.TRTCCalling.EVENT.USER_ENTER, this.handlecaaUserEnter)
      // 用户退出房间
      this.trtcCalling.off(window.TRTCCalling.EVENT.USER_LEAVE, this.handleUserLeave)
      // 重复登录，被踢出房间
      this.trtcCalling.off(window.TRTCCalling.EVENT.KICKED_OUT, this.handleKickedOut)
      // 远端用户开启/关闭了摄像头
      this.trtcCalling.off(window.TRTCCalling.EVENT.USER_VIDEO_AVAILABLE, this.handleUserVideoChange)
      // 远端用户开启/关闭了麦克风
      this.trtcCalling.off(window.TRTCCalling.EVENT.USER_AUDIO_AVAILABLE, this.handleUserAudioChange)
      // 本次通话结束
      this.trtcCalling.off(window.TRTCCalling.EVENT.CALLING_END, this.handleCallEnd)
      // 错误回调
      this.trtcCalling.off(window.TRTCCalling.EVENT.ERROR, this.handleError)
    },
    // 被邀用户拒绝通话
    async handleInviteeReject({ userID }) {
      console.log('被邀用户拒绝通话------------------')
      this.statusName = '对方忙'
      this.handleCancel(true)
    },
    // 被邀用户正在通话中，忙线
    async handleInviteeLineBusy({ userID }) {
      console.log('被邀用户正在通话中，忙线------------------')
      this.statusName = '正在通话中，请稍后再呼'
    },
    // 被邀用户超时无应答
    handleNoResponse({ userID }) {
      console.log('被邀用户超时无应答------------------')
      this.statusName = '无应答'
      this.handleCancel(true)
    },
    // 用户进房
    handlecaaUserEnter({ userID }) {
      console.log('用户进房------------------', userID)
      this.statusName = '接听'
      this.trtcCalling.startRemoteView({
        userID: userID,
        videoViewDomID: 'video-big'
      })
      this.trtcCalling.startLocalView({
        userID: this.user.phone,
        videoViewDomID: 'video-small'
      })
      this.$nextTick(() => {
        this.statusName = '接听'
        this.setDuration()
      })
    },
    // 用户退出房间
    handleUserLeave({ userID }) {
      console.log('用户退出房间------------------', userID)
      this.statusName = ''
    },
    // 重复登录，被踢出房间
    handleKickedOut() {
      console.log('重复登录，被踢出房间------------------')
      this.statusName = ''
      this.isShow = false
      this.trtcCalling.logout()
    },
    // 远端用户开启/关闭了摄像头
    handleUserVideoChange({ userID, isVideoAvailable }) {
      console.log('远端用户开启/关闭了摄像头------------------', isVideoAvailable)
    },
    // 本地用户开启/关闭了摄像头
    handleChangeVideoAvailable() {
      if (this.isVideoAvailable) {
        this.trtcCalling.closeCamera()
      } else {
        this.trtcCalling.openCamera()
      }
      this.isVideoAvailable = !this.isVideoAvailable
    },
    // 远端用户开启/关闭了麦克风
    handleUserAudioChange({ userID, isAudioAvailable }) {
      console.log('远端用户开启/关闭了麦克风------------------', isAudioAvailable)
    },
    handleChangeAudioAvailable() {
      this.isAudioAvailable = !this.isAudioAvailable
      this.trtcCalling.setMicMute(this.isAudioAvailable)
    },
    // 本次通话结束
    handleCallEnd() {
      console.log('本次通话结束------------------')
      this.statusName = ''
      this.handleCancel(false)
    },
    // 错误回调
    handleError() {
      console.log('错误回调------------------')
    },
    // 双方切换视频
    handleVideoClick(event) {
      this.isVideoClick = true
      console.log(event)
      this.videoChangeFlag = !this.videoChangeFlag
      if (this.videoChangeFlag) {
        this.trtcCalling.stopRemoteView({
          userID: this.callPerson.telephone,
          videoViewDomID: 'video-small'
        })
        this.trtcCalling.stopLocalView({
          userID: this.user.phone,
          videoViewDomID: 'video-big'
        })
        // 远程在大框
        this.bigUserName = this.callPerson.gridPersonName
        this.smallUserName = this.user.userName
        this.trtcCalling.startRemoteView({
          userID: this.callPerson.telephone,
          videoViewDomID: 'video-big'
        })
        this.trtcCalling.startLocalView({
          userID: this.user.phone,
          videoViewDomID: 'video-small'
        })
      } else {
        this.trtcCalling.stopRemoteView({
          userID: this.callPerson.telephone,
          videoViewDomID: 'video-big'
        })
        this.trtcCalling.stopLocalView({
          userID: this.user.phone,
          videoViewDomID: 'video-small'
        })
        // 远程在小框
        this.bigUserName = this.user.userName
        this.smallUserName = this.callPerson.gridPersonName
        this.trtcCalling.startRemoteView({
          userID: this.callPerson.telephone,
          videoViewDomID: 'video-small'
        })
        this.trtcCalling.startLocalView({
          userID: this.user.phone,
          videoViewDomID: 'video-big'
        })
      }
    },
    // 计时
    setDuration() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.duration = 0
      this.durationFormat = formatTimes.formatDuration(this.duration)
      this.timer = setInterval(() => {
        this.duration += 1
        this.durationFormat = formatTimes.formatDuration(this.duration)
      }, 1000)
    }
  },
  beforeDestroy() {
    // localStorage.clear()
    this.removeListener()
    this.trtcCalling.logout()
  }
}
</script>
<style scoped lang="less">
@import '../style/index.less';
</style>
